<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="请选择采样信息" @ok="handleSubmit">
    <BasicTable @register="registerTable" />
  </BasicModal>
</template>

<script lang="ts">
import { defineComponent, ref, } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicTable, useTable, } from '/@/components/Table';
import { useMessage } from '/@/hooks/web/useMessage';

import { searchFormSchemaCheckItem } from '../plan/data';
import { getCheckItemList } from '/@/api/project/planDetail';
import { add as addDetail, } from '/@/api/project/reasonDetail';


export default defineComponent({
  name: 'checkItemModal',
  components: { BasicModal, BasicTable },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    const isUpdate = ref(true);

    //采样信息列表
    const [registerTable, { reload, getSelectRows, }] = useTable({
      api: getCheckItemList,
      rowSelection: {
        type: 'checkbox',
        columnWidth: 30,
      },
      columns: [
        {
          title: '检测类别',
          dataIndex: 'checkType',
        }, {
          title: '检测项',
          dataIndex: 'checkItem',
        }, {
          title: '类别',
          dataIndex: 'checkSubtype',
        }, {
          title: '检测方法',
          dataIndex: 'checkStandard',
        }, {
          title: '采集或保存方法',
          dataIndex: 'collectWay',
        },],
      formConfig: {
        labelWidth: 120,
        schemas: searchFormSchemaCheckItem,
        showAdvancedButton: false,
        showResetButton: false,
        autoSubmitOnEnter: true,
      },
      canColDrag: true,
      useSearchForm: true,
      bordered: true,
      showIndexColumn: true,
    });

    const reasonId = ref(0);
    const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
      reasonId.value = data.reasonId;
      //console.log('采样计划id=', planId.value);
    });

    const { createMessage } = useMessage();
    async function handleSubmit() {
      try {
        setModalProps({ confirmLoading: true });
        const selectedRows = getSelectRows();
        console.log('selectedRows', selectedRows);
        if (selectedRows.length === 0) {
          createMessage.success({
            content: '请至少选择一条采样信息',
            duration: 1,
          });
          return
        }
        // 处理选中的数据
        selectedRows.forEach((item) => {
          item.id = null; // 重置ID
          item.reasonId = reasonId.value; // 设置委托依据ID
          addDetail(item);
        });

        emit('success', selectedRows);
        closeModal();
      } finally {
        setModalProps({ confirmLoading: false });
      }
    }

    return { registerModal, registerTable, handleSubmit };
  },
});
</script>
